/**
 * Copyright c OLE CORPORATION 2014 All Rights Reserved. 
 * JsonUtil.java　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　
 */
package com.e_manager.soft.emanager.util;

import com.google.gson.Gson;
import org.apache.log4j.Logger;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * [JsonUtil]<br>
 * java对象和JSON字符串相互转化工具类<br>
 * <br>
 * [功能概要]<br>
 * java对象和JSON字符串相互转化<br>
 * <br>
 * [更新履历]<br>
 *
 * @author jys
 * @version 1.00
 */
public final class JsonUtil {
	private static final Logger logger = Logger.getLogger(JsonUtil.class);
	private JsonUtil() {
	}

	/**
	 * 对象转换成json字符串
	 * 
	 * @param obj
	 * @return
	 */
	public static String toJson(Object obj) {
		Gson gson = new Gson();
		/** 日志实例 */
//	  Logger logger = Logger.getLogger(JsonUtil.class);
		logger.info("返回值长度===================>"+ gson.toJson(obj).length());
		return gson.toJson(obj);
	}

	/**
	 * json字符串转成对象
	 * 
	 * @param str
	 * @param type
	 * @return
	 */
	public static <T> T fromJson(String str, Type type) {
		Gson gson = new Gson();
		// str = str.replaceAll("=,", "='',");
		return gson.fromJson(str, type);
	}

	/**
	 * json字符串转成对象
	 * 
	 * @param str
	 * @param type
	 * @return
	 */
	public static <T> T fromJson(String str, Class<T> type) {
		Gson gson = new Gson();
		return gson.fromJson(str, type);
	}

	
	
	 @SuppressWarnings({ "unchecked", "null" })
	public static Map<String, Object> jsonToMap(String jsonStr) {
	        Map<String, Object> resultMap = null;
	        Gson gson = new Gson();
	        try {
	            resultMap = gson.fromJson(jsonStr, resultMap.getClass());
	        } catch (Exception e) {
	            return null;
	        }
	        return resultMap;
	    }

	    @SuppressWarnings("rawtypes")
		public static String mapToJson(Map jsonMap) {
	        String resultJson = null;
	        Gson gson = new Gson();
	        try {
	            resultJson = gson.toJson(jsonMap);
	        } catch (Exception e) {
	            return null;
	        }
	        return resultJson;
	    }

	    public static <T> T jsonToObject(String jsonStr, Class<T> cls) {
	        T resultT = null;
	        Gson gson = new Gson();
	        try {
	            resultT = gson.fromJson(jsonStr, cls);
	        } catch (Exception e) {
	            return null;
	        }
	        return resultT;
	    }

	    public static String objectToJson(Object obj) {
	        String resultJson = null;
	        Gson gson = new Gson();
	        try {
	            resultJson = gson.toJson(obj);
	        } catch (Exception e) {
	            return null;
	        }
	        return resultJson;
	    }
}
